<template>
  <div class="index-container">
    <div class="table-header-btn-wrap" style="height: 30px">
      <el-input v-model="query.keyword" class="m-2" placeholder="通过房间号进行搜索..."
                style="margin-right: 20px;width: 280px"></el-input>
      <el-button @click="onClickSearch" v-loading="listLoading">搜索</el-button>
      <el-button @click="create" v-loading="listLoading">添加房间</el-button>
    </div>
    <div class="table-wrap" style="height: calc(100% - 100px)">
      <el-table :data="rooms" border v-loading="listLoading" height="100%" :empty-text="'数据为空'">


        <el-table-column prop="number" label="房号" width="120px">
        </el-table-column>
        <el-table-column prop="type" label="类型" width="200px">
          <template #default="scope">
            <span v-if="scope.row.type">{{ scope.row.type.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="费用" width="70px">
          <template #default="scope">
            <span v-if="scope.row.type">{{ scope.row.type.price }}元</span>
          </template>
        </el-table-column>
        <el-table-column prop="excerpt" label="封面" width="200px">
          <template #default="scope">
            <img style="width: 170px" v-if="scope.row.type"
                 :src="uploadServer +  '/upload/image/' +scope.row.type.photo"
                 class="avatar"/>
          </template>
        </el-table-column>
        <el-table-column prop="floor" label="楼层位置" width="220px">
        </el-table-column>

        <el-table-column prop="status" label="状态" width="100px">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 'NORMAL'">正常</el-tag>
            <el-tag type="danger" v-else-if="scope.row.status === 'DISABLED'">禁用</el-tag>
          </template>
        </el-table-column>


        <el-table-column prop="excerpt" label="操作" width="260px">
          <template #default="scope">
            <el-button type="success" @click="edit(scope.row)">修改</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="page-wrap"
         style="height: 40px;margin-top: 20px;display: flex;align-items: center;justify-content: space-between;">
      <div class="span" style="font-size: 14px;color: #333;margin-right: 20px;">总数：{{ total }}</div>
      <el-pagination
          small
          background
          layout="prev, pager, next"
          :total="total"
          :current-page="query.page"
          class="mt-4"
          @current-change="pageChange"
          :page-size="query.page_size"
      />
    </div>

    <el-dialog v-model="createDialog" :title="dialogModel==='create'?'添加房间':'修改房间'" width="760px"
               :close-on-click-modal="false"
    >
      <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rulesType"
          label-width="80px"
          class="demo-ruleForm"
          status-icon
      >
        <el-form-item label="房号" prop="number" style="max-width: 300px;width: 100%">
          <el-input v-model="ruleForm.number"/>
        </el-form-item>
        <el-form-item label="楼层位置" prop="floor" style="max-width: 300px;width: 100%">
          <el-input v-model="ruleForm.floor"/>
        </el-form-item>
        <el-form-item label="类型" prop="typeId" style="max-width: 300px;width: 100%">
          <el-select v-model="ruleForm.typeId" placeholder="请选择房间类型">
            <el-option v-for="item in types" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status" style="max-width: 300px;width: 100%">
          <el-select v-model="ruleForm.status">
            <el-option label="正常" value="NORMAL"></el-option>
            <el-option label="禁用" value="DISABLED"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)" v-if="dialogModel === 'create'">
            添加
          </el-button>
          <el-button type="primary" @click="submitEditForm(ruleFormRef)" v-else>
            修改
          </el-button>
        </el-form-item>

      </el-form>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {computed, onMounted, reactive, ref} from "vue";
import $api from "@/api";
import {useRouter} from "vue-router";
import {ElMessage, ElMessageBox, ElNotification} from 'element-plus'
import type {FormInstance, FormRules, UploadProps} from "element-plus";
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import TypeSelect from '@/components/TypeSelect.vue'

const locale = zhCn
const router = useRouter()
const uploadServer = import.meta.env.VITE_SERVER


const dialogModel = ref('create') //create edit
const createDialog = ref(false)
var createLoading = ref(false)
const create = () => {
  dialogModel.value = 'create'
  createDialog.value = true
  ruleForm.id = null
  ruleForm.number = ''
  ruleForm.floor = ''
  ruleForm.status = 'NORMAL'
  ruleForm.typeId = ''
}
const edit = (row: any) => {
  dialogModel.value = 'edit'
  createDialog.value = true
  ruleForm.id = row.id
  ruleForm.number = row.number
  ruleForm.floor = row.floor
  ruleForm.status = row.status
  ruleForm.typeId = row.typeId
}
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  id: null,
  number: '',
  floor: '',
  status: 'NORMAL',
  typeId: ''
})
const rulesType = reactive<FormRules>({
  number: [
    {required: true, message: '请输入房间编号', trigger: 'blur'},
    {min: 1, max: 30, message: '长度限制在 1 ~ 30 个字符', trigger: 'blur'},
  ],
  typeId: [
    {required: true, message: '请选择房间类型', trigger: 'blur'},
  ],
})
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (createLoading.value) {
        return
      }
      createLoading.value = true
      $api.roomApi.create(ruleForm).then(res => {
        createLoading.value = false
        ElNotification({
          title: '成功',
          message: '创建房间成功！',
          type: 'success',
        })
        createDialog.value = false
        search()
      }).catch(() => {
        createLoading.value = false
      })
    } else {

    }
  })
}

onMounted(() => {
  search()
  getType()
})

/**
 * 查询房间
 */

var listLoading = ref(false) //列表接口是否在加载

const total = ref(0) //总数

const query = reactive({
  page: 1,
  page_size: 20,
  keyword: ''
})
const pageChange = (page: number) => {
  query.page = page
  getList()
}
const onClickSearch = () => {
  search()
}

const search = () => {
  query.page = 1
  getList()
}

const rooms = ref([])
const getList = () => {
  listLoading.value = true
  $api.roomApi.fetchListJoinType(query).then((res: any) => {
    total.value = res.total
    rooms.value = res.results
    listLoading.value = false
  }).catch(() => {
    listLoading.value = false
  })
}

/**
 * @description 修改房间
 * @param formEl
 */
const submitEditForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (createLoading.value) {
        return
      }
      createLoading.value = true
      $api.roomApi.edit(ruleForm).then(res => {
        createLoading.value = false
        ElNotification({
          title: '成功',
          message: '修改房间成功！',
          type: 'success',
        })
        createDialog.value = false
        search()
      }).catch(() => {
        createLoading.value = false
      })
    } else {

    }
  })
}
/**
 * 获取所有type
 */
const types = ref([])
const getType = () => {
  $api.typeApi.list({page: 1, page_size: 9999}).then(res => {
    types.value = res.results
  })
}
</script>
<style scoped lang="scss">
.index-container {
  padding: 20px;
  width: 100%;
  height: 100%;
}

.table-wrap {
  margin-top: 20px;
}

.excerpt {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
</style>